package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class GetMRTCmapping
 */
//@WebServlet(description = "取得該測試項目所對應的測試案例", urlPatterns = { "/GetMRTCmapping" })
public class GetMRTCmapping extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetMRTCmapping() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Widgets wid = new Widgets();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String strSQL = "SELECT t3.tcID, t1.uID,t1.tcName FROM tms_testcase t1,tms_mrtcmapping t2,tms_tcidmapping t3 WHERE  t3.active=1 AND t3.uID=t2.tcuid AND t2.mrid=? AND t2.tpid=? AND t2.tcuid = t1.uID";
		String returnResult = "";
		
		String mrid = request.getParameter("mrid");
		int tpid = Integer.parseInt(request.getParameter("tpid"));
		
		ArrayList<TestCase> testCases = new ArrayList<TestCase>();
		
		try {
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, mrid);
			ps.setInt(2, tpid);
			rs = ps.executeQuery();
			
			while (rs.next()) {
				TestCase testCase = new TestCase();
				testCase.setuID(rs.getInt("uID"));
				testCase.setTcName(rs.getString("tcName"));
				testCase.setTcID(rs.getString("tcID"));
				testCases.add(testCase);
			}
			
			returnResult = new Gson().toJson(testCases);
			returnResult = returnResult.replace("[", "{\"sqlData\":[")+ ",\"strSQL\":\""+strSQL+"\",\"size\":\""+testCases.size()+"\"}";
			
		} catch (SQLException e) {
			returnResult = "{\"errorMsg\":\""+wid.keepErrorMes(conn, ps, e,"", true)+"\"}";
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				returnResult = "{\"errorMsg\":\""+e.toString()+"\"}";
			}
		}
		
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(returnResult);
		
	}

}
